package com.zg.common.lock.demo;

import com.zg.common.core.R;
import com.zg.common.lock.service.LockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/5/21 9:28
 */

@RequiredArgsConstructor
@Slf4j
public class Demo {

    private final LockService lockService;
    public void locked(){
        boolean locked = false;
        try {
            // 尝试获取锁，最多等待5秒，锁自动过期时间30秒
            locked = lockService.tryLock("resourceLock", 5, 30, TimeUnit.SECONDS);
            if (locked) {
                // 获取锁成功，执行业务逻辑
                Thread.sleep(2000); // 模拟业务处理
                log.info("加锁成功，业务处理完成");
            } else {
                log.info("获取锁失败");
            }
        } catch (Exception e) {
            log.error("处理异常", e);
        }
        finally {
            if (locked) {
                lockService.unlock("resourceLock");
            }
        }
    }
}
